﻿using Abp.Authorization;
using Abp.BackgroundJobs;
using Abp.Runtime.Session;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Mt.Site.Application.ContentManagement.Dto;
using Mt.Site.Core.Configuration;
using Mt.Site.Core.ContentManagement.Permissions;
using System.Threading.Tasks;

namespace Mt.Site.Application.ContentManagement
{
    public class ContentRouteAppService : MtSiteAppServiceBase, IContentRouteAppService
    {
        private readonly IBackgroundJobManager _backgroundJobManager;

        private readonly ContentRouteGeneratingHelper _contentRouteGeneratingHelper;

        private readonly IConfigurationRoot _appConfiguration;

        public ContentRouteAppService(
            ContentRouteGeneratingHelper contentRouteGeneratingHelper,
            IBackgroundJobManager backgroundJobManager,
            IAppConfigurationAccessor configurationAccessor)
        {
            _contentRouteGeneratingHelper = contentRouteGeneratingHelper;
            _backgroundJobManager = backgroundJobManager;

            _appConfiguration = configurationAccessor.Configuration;
        }

        [HttpPost]
        [AbpAuthorize(ContentPermissions.Pages_Manage_Content_Create, ContentPermissions.Pages_Manage_Content_Update, 
            RequireAllPermissions = false)]
        public async Task GenerateDetailPageUrlAsync()
        {
            //1. 需要一个一键生成功能来更新旧数据的路由数据（如果列表页的自定义路由修改了，详情页就需要这个批量修改路由的功能）
            //2. 今后新增的数据 （生成路由数据）

            bool byBackgroundJob = false;
            if (MtSiteConsts2.BackgroundJobs)
            {
                var hangfireEnable = _appConfiguration["App:HangfireEnable"];
                if (hangfireEnable == "true")
                {
                    byBackgroundJob = true;

                    await _backgroundJobManager.EnqueueAsync<ContentRouteGeneratingJob, ContentRouteGeneratingJobArgs>(new ContentRouteGeneratingJobArgs
                    {
                        TenantId = AbpSession.GetTenantId()
                    });
                }
            }

            if (!byBackgroundJob)
            {
                await _contentRouteGeneratingHelper.GenerateContentUrlAsync();
                await _contentRouteGeneratingHelper.GenerateContent2UrlAsync();
            }
        }
    }
}
